﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Services;
using DNNspot.LiveChat.DataModel;
using DotNetNuke.Entities.Users;
using EntitySpaces.DynamicQuery;
using EntitySpaces.Interfaces;
using DNNspot.LiveChat.Common;

namespace DNNspot.LiveChat.Admin
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class SessionHandler : IHttpHandler
    {
        // PRIVATE MEMBERS #######################################################

        // PUBLIC METHODS ########################################################

        public void ProcessRequest(HttpContext context)
        {
            var request = context.Request;
            var response = context.Response;

            context.Response.Expires = -1;
            context.Response.ContentType = "application/json";

            InitializeProvider();

            response.Write(BuildOutputString(request));
            response.Flush();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        // PRIVATE METHODS #######################################################

        private static FlexigridSearchCriteria BuildSessionSearchCriteria(HttpRequest request)
        {
            var searchCriteria = new FlexigridSearchCriteria();

            searchCriteria.PageNumber = Convert.ToInt32(request.Params[Params.PageNumber]);
            searchCriteria.PageSize = Convert.ToInt32(request.Params[Params.PageSize]);
            searchCriteria.Query = request.Params[Params.Query];
            searchCriteria.QueryColumns = request.Params[Params.QueryColumns];
            searchCriteria.SortColumn = request.Params[Params.SortColumn];
            searchCriteria.SortDirection = esOrderByDirection.Unassigned;

            var sortOrder = request.Params[Params.SortDirection].ToLower();

            if (sortOrder.Equals("asc"))
                searchCriteria.SortDirection = esOrderByDirection.Ascending;
            else if (sortOrder.Equals("desc"))
                searchCriteria.SortDirection = esOrderByDirection.Descending;

            return searchCriteria;
        }

        private static string BuildOutputString(HttpRequest request)
        {
            var output = string.Empty;
            var rowOutput = string.Empty;

            var searchCriteria = BuildSessionSearchCriteria(request);
            var sessions = SessionCollection.Search(searchCriteria);
            var total = SessionCollection.GetTotal(searchCriteria);

            foreach (Session session in sessions)
            {
                if (rowOutput.Length > 0)
                    rowOutput += ",";

                var firstName = string.Empty;
                var lastName = string.Empty;

                var agent = new Agent();

                if (session.AgentId != null)
                {
                    agent.LoadByPrimaryKey((int)session.AgentId);

                    if (agent.UserId != null)
                    {
                        var user = UserController.GetUserById((int)agent.PortalId, (int)agent.UserId);
                        if (user != null)
                        {
                            firstName = user.FirstName;
                            lastName = user.LastName;
                        }
                    }
                }

                rowOutput += string.Format("{{id:{0},cell:['{1}','{2}','{3}','{4}']}}",
                        session.SessionId,
                        Convert.ToDateTime(session.CreatedDate),
                        Convert.ToBoolean(session.IsActive) ? "" : Convert.ToDateTime(session.ModifiedDate).ToString(),
                        string.Format("{0} {1}", firstName, lastName).Replace("'", "\\'"),
                        Convert.ToBoolean(session.IsActive) ? "Open" : "Closed"
                        );
            }

            output += string.Format("{{ page: {0}, total: {1}, rows: [{2}]}}", searchCriteria.PageNumber, total, rowOutput);

            return output;
        }

        private static void InitializeProvider()
        {
            if (esConfigSettings.ConnectionInfo.Default != "SiteSqlServer")
            {
                esConfigSettings connectionInfoSettings = esConfigSettings.ConnectionInfo;
                foreach (esConnectionElement connection in connectionInfoSettings.Connections)
                {
                    //if there is a SiteSqlServer in es connections set it default
                    if (connection.Name == "SiteSqlServer")
                    {
                        esConfigSettings.ConnectionInfo.Default = connection.Name;
                        return;
                    }
                }

                //no SiteSqlServer found grab dnn cnn string and create
                string dnnConnection = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;

                // Manually register a connection
                esConnectionElement conn = new esConnectionElement();
                conn.ConnectionString = dnnConnection;
                conn.Name = "SiteSqlServer";
                conn.Provider = "EntitySpaces.SqlClientProvider";
                conn.ProviderClass = "DataProvider";
                conn.SqlAccessType = esSqlAccessType.DynamicSQL;
                conn.ProviderMetadataKey = "esDefault";
                conn.DatabaseVersion = "2005";

                // Assign the Default Connection
                esConfigSettings.ConnectionInfo.Connections.Add(conn);
                esConfigSettings.ConnectionInfo.Default = "SiteSqlServer";

                // Register the Loader
                esProviderFactory.Factory = new EntitySpaces.LoaderMT.esDataProviderFactory();
            }
        }
    }
}
